/*
* @Author: 窦子滨<zibin_5257@163.com>
* @Date: 2019-09-02 14:16
 */

package main

//带参数的定时任务
import (
	"io/ioutil"
	"net/http"
	"net/url"
	//"fmt"
	"time"
)

//添加单个任务
func AddJob(v *Task) {
	c.AddJob(v, func(*Task) {
		getUrl(v)
	})
}

/**
获取url的信息
*/
func getUrl(info *Task) {
	task_id:=info.Id
	var elapsed int64

	u, _ := url.Parse(info.Url)
	q := u.Query()
	u.RawQuery = q.Encode()

	tr := &http.Transport{
		DisableKeepAlives: true,
	}
	client := &http.Client{Transport: tr, Timeout: time.Second * time.Duration(info.Timeout)}

	t1 := time.Now() // get current time

	resp, err := client.Get(u.String())
	elapsed = time.Since(t1).Round(time.Millisecond).Nanoseconds() / 1000000

	if err != nil {
		Log.Info("URL链接打开失败！%s", err)
		write_log(task_id, 0, elapsed, "", err.Error())
		return
	}

	defer resp.Body.Close()

	if info.SaveBody == "1" {
		body, err := ioutil.ReadAll(resp.Body)

		if (err != nil) {
			Log.Info("URL链接内容获取失败！%s", err)
			write_log(task_id, resp.StatusCode, elapsed, "", err.Error())
			return
		}

		write_log(task_id, resp.StatusCode, elapsed, string(body), "")
		return
	}

	write_log(task_id, resp.StatusCode, elapsed, "", "")
}
